package org.jakim.servlets;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.jakim.entity.AdditionaInfo;
import org.jakim.entity.Education;
import org.jakim.entity.Language;
import org.jakim.entity.PersonalInforamation;
import org.jakim.entity.PersonalSkill;
import org.jakim.entity.UserAddress;
import org.jakim.entity.WorkExperience;

/**
 * Servlet implementation class AddInfo
 */

public class AddInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddInfo() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int numberCVWizardStep = Integer.valueOf(request
				.getParameter("numberCVWizardStep"));

		switch (numberCVWizardStep) {
		case 0:
			this.addPersonalInfo(request);
			response.sendRedirect("cvwizard/jobhistorywizard.jsp");
			break;
		case 1:
			this.addWorkExperience(request);
			response.sendRedirect("cvwizard/jobhistorywizard.jsp");
			break;
		case 2:
			this.addEducation(request);
			response.sendRedirect("cvwizard/educationwizard.jsp");
			break;
		case 3:
			this.addPersonalSkills(request);
			response.sendRedirect("cvwizard/personalskillswizard.jsp");
			break;
		case 4:
			this.addLanguage(request);
			response.sendRedirect("cvwizard/languageswizard.jsp");
			break;
		case 5:
			this.addOthers(request);
			response.sendRedirect("cvwizard/additionalinformationwizard.jsp");
			break;
		}
	}

	private void addPersonalInfo(HttpServletRequest request) {
		HttpSession httpSeesion = request.getSession();
		PersonalInforamation userPersonalInfo = null;
		Object objPersonalInfo = httpSeesion.getAttribute("attrPersonalInfo");
		
		boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
		if (isMultipartContent) {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {
				List<FileItem> fields = upload.parseRequest(request);
				Iterator<FileItem> it = fields.iterator();
				
				while (it.hasNext()) {
					FileItem fileItem = it.next();
					boolean isFormField = fileItem.isFormField();
					
		}
		
		if ((objPersonalInfo != null)
				&& (objPersonalInfo instanceof PersonalInforamation)) {
			userPersonalInfo = (PersonalInforamation) objPersonalInfo;
		} else {

			UserAddress userAddress = new UserAddress();

			userAddress.setStateName(request
					.getParameter("personalInfoStateName"));
			userAddress.setCityName(request.getParameter("personalInfoCity"));
			userAddress.setStreetName(request
					.getParameter("personalInfoStreetName"));
			userAddress.setStreetNumber(request
					.getParameter("personalInfoStreetNumber"));
			userAddress.setAppartmentNumber(Integer.parseInt(request
					.getParameter("personalInfoApartment")));
			userAddress.setFloorNumber(request
					.getParameter("personalInfoFloorNumber"));
			userAddress.setZipNumber(request
					.getParameter("personalInfoZipNumber"));

			userPersonalInfo = new PersonalInforamation();

			String strBirthDate = request.getParameter("personalInfoBirthDate");

			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date birthDate = null;

			try {
				Pattern datePattern = Pattern
						.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
				Matcher dateMatcher = datePattern.matcher(strBirthDate);
				birthDate = dateMatcher.matches() ? df.parse(strBirthDate)
						: null;
			} catch (ParseException e) {
				e.printStackTrace();
			}

			userPersonalInfo.setUserBirthDay(birthDate);
			userPersonalInfo.setUserAddress(userAddress);
			userPersonalInfo.setUserName(request
					.getParameter("personalInfoFirstName"));
			userPersonalInfo.setUserSirName(request
					.getParameter("personalInfoSirName"));
			// userPersonalInfo.setUserPhoto(request.getParameter("personalInfoPhoto"));
			userPersonalInfo.setUserNationality(request
					.getParameter("personalInfoNationality"));
			userPersonalInfo.setUserEmail(request
					.getParameter("personalInfoEmail"));
			userPersonalInfo.setPhoneNumber(request
					.getParameter("personalInfoPhone"));
			userPersonalInfo.setUserGender(request
					.getParameter("personalInfoGender"));
		}

		httpSeesion.setAttribute("attrPersonalInfo", userPersonalInfo);
	}

	@SuppressWarnings("unchecked")
	private void addWorkExperience(HttpServletRequest request) {
		HttpSession httpSeesion = request.getSession();
		List<WorkExperience> listWorkExperience = null;
		Object objWrokExperience = httpSeesion
				.getAttribute("attrWrokExperience");

		if (objWrokExperience == null) {
			listWorkExperience = new ArrayList<WorkExperience>();
			httpSeesion.setAttribute("attrWrokExperience", listWorkExperience);
		} else {
			if (objWrokExperience instanceof List<?>) {
				listWorkExperience = (List<WorkExperience>) objWrokExperience;
			}
		}

		String strStartDate = request.getParameter("workStartDate");
		String strEndDate = request.getParameter("workEndDate");

		WorkExperience work = new WorkExperience();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate = null;
		Date endDate = null;

		try {
			Pattern datePattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
			Matcher dateMatcher = datePattern.matcher(strEndDate);
			endDate = dateMatcher.matches() ? df.parse(strEndDate) : null;

			dateMatcher = datePattern.matcher(strStartDate);
			startDate = dateMatcher.matches() ? df.parse(strStartDate) : null;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		work.setWorkEndDate(endDate);
		work.setWorkStartDate(startDate);
		work.setEmployerAddress(request.getParameter("workEmployerAddress"));
		work.setEmployerFirstName(request.getParameter("workEmployerName"));
		work.setEmployerSirName(request.getParameter("workEmployerSirName"));
		work.setWorkBusinessSector(request.getParameter("workType"));
		work.setWorkMainActivities(request.getParameter("workMainActiviteis"));
		work.setWorkOccupation(request.getParameter("workOccupation"));

		listWorkExperience.add(work);
		request.getSession().setAttribute("attrWrokExperience",
				listWorkExperience);
	}

	private void addEducation(HttpServletRequest request) {
		HttpSession httpSeesion = request.getSession();
		List<Education> listEducationAndSkills = null;

		Object objEducationAndSkills = httpSeesion
				.getAttribute("attrEducationAndSkills");

		if (objEducationAndSkills == null) {
			listEducationAndSkills = new ArrayList<Education>();
			httpSeesion.setAttribute("attrEducationAndSkills",
					listEducationAndSkills);
		} else {
			if (objEducationAndSkills instanceof List<?>) {
				listEducationAndSkills = (List<Education>) objEducationAndSkills;
			}
		}

		Education education = new Education();

		String strStartDate = request.getParameter("educationStartDate");
		String strEndDate = request.getParameter("educationEndDate");

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate = null;
		Date endDate = null;

		try {
			Pattern datePattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
			Matcher dateMatcher = datePattern.matcher(strEndDate);
			endDate = dateMatcher.matches() ? df.parse(strEndDate) : null;

			dateMatcher = datePattern.matcher(strStartDate);
			startDate = dateMatcher.matches() ? df.parse(strStartDate) : null;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		education.setEducationStartDate(startDate);
		education.setEducationEndDate(endDate);

		education.setEducationOccupationalSkills(request.getParameter(request
				.getParameter("educationCoveredSkills")));
		education.setEducationOrganisationName(request
				.getParameter("educationOrganisationName"));
		education.setEducationOrganisationType(request
				.getParameter("educationOrganisationType"));
		education.setEducationStreet(request
				.getParameter("educationOrganisationStreet"));
		education.setEducationCity(request
				.getParameter("educationOrganisationCity"));
		education.setEducationPostalCode(Integer.valueOf(request
				.getParameter("educationOrganisationPostalCode")));
		education.setEducationCountry(request
				.getParameter("educationOrganisationCountry"));
		education.setEducationClassificationLevel(request
				.getParameter("educationClassificationLevel"));
		education.setEducationOrganiztaionField(request
				.getParameter("educationField"));
		education.setEducationQualificationTitle(request
				.getParameter("educationQualificationTitle"));

		listEducationAndSkills.add(education);
	}

	@SuppressWarnings("unchecked")
	private void addLanguage(HttpServletRequest request) {
		HttpSession httpSeesion = request.getSession();
		PersonalSkill personalSkill = null;
		
		Object objPersonalSkill = httpSeesion.getAttribute("attrPersonalSkills");

		if ((objPersonalSkill != null) && (objPersonalSkill instanceof PersonalSkill)) {
			personalSkill = (PersonalSkill) objPersonalSkill;

		}else{ 
			personalSkill = new PersonalSkill();
		}
		
		if (personalSkill.getOtherLanguages() == null){
			personalSkill.setOtherLanguages(new HashSet<Language>());
		}

		String motherLang = request.getParameter("motherLanguageName");
		if (motherLang != null && !motherLang.isEmpty()){
			((PersonalSkill) objPersonalSkill).setMotherLanguage(motherLang);
		}
		
		Language language = new Language();
		language.setLanguageName(request.getParameter("languageName"));
		language.setLanguageListening(request.getParameter("languageListening"));
		language.setLanguageReading(request.getParameter("languageReading"));
		language.setLanguageInteraction(request
				.getParameter("languageInteraction"));
		language.setLanguageProduction(request
				.getParameter("languageProduction"));
		language.setLanguageWriting(request.getParameter("languageWriting"));
		personalSkill.getOtherLanguages().add(language);
		
		httpSeesion.setAttribute("attrPersonalSkills", objPersonalSkill);
	}

	private void addPersonalSkills(HttpServletRequest request) {
		HttpSession httpSeesion = request.getSession();
		Object objPersonalSkills = httpSeesion
				.getAttribute("attrPersonalSkills");
		PersonalSkill personalSkills = null;
		
		if (objPersonalSkills == null) {
			personalSkills = new PersonalSkill();
			personalSkills.setSkillSocial(request.getParameter("skillSocial"));
			personalSkills.setSkillOranisational(request.getParameter("skillOrganizational"));
			personalSkills.setSkillTechnical(request.getParameter("skillTechnical"));
			personalSkills.setSkillArtistic(request.getParameter("skillArtistic"));
			personalSkills.setSkillComputer(request.getParameter("skillComputer"));
			personalSkills.setSkillOther(request.getParameter("skillOther"));

			StringBuffer result = new StringBuffer();
			for (String license : request.getParameterValues("drivingLincense")) {
				result.append(license).append(",");
			}

			personalSkills.setSkillDrivingLicence(result.deleteCharAt(
					result.length() - 1).toString());
		}else{
			personalSkills = (PersonalSkill) objPersonalSkills;
		}

		httpSeesion.setAttribute("attrPersonalSkills", personalSkills);
	}

	private void addOthers(HttpServletRequest request) {
		HttpSession httpSeesion = request.getSession();
		AdditionaInfo additionalInfo = null;

		Object objAdditionalInfo = httpSeesion
				.getAttribute("attrAdditionalInfo");

		if (objAdditionalInfo == null) {
			additionalInfo = new AdditionaInfo();
		} else {
			if (objAdditionalInfo instanceof AdditionaInfo) {
				additionalInfo = (AdditionaInfo) objAdditionalInfo;
			}
		}

		// additionalInfo.(personalInfo)(request.getParameter("additionalInfo"));
		// additionalInfo.setAnnexes(request.getParameter("additionalAnnex"));

		httpSeesion.setAttribute("attrAdditionalInfo", additionalInfo);
	}
}
